package com.xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName ExceptionCatch
 * @Description (统一异常捕获类)
 * @date 2020/1/19 9:43
 * @since V1.0
 */
@ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCast.class);

    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTION;
    //使用builder来构建一个异常类型和错误代码的异常
    protected  static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    static{
        //在这里加入一些基础的异常类型判断
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult catchCustomException(CustomException customException){
        //打印错误日志
        LOGGER.error("catch exception:{}",customException.getMessage());
        return new ResponseResult(customException.getResultCode());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult catchException(Exception exception){
        //打印错误日志
        LOGGER.error("catch exception:{}",exception.getMessage());
        exception.printStackTrace();
        //判断是否为空
        if (EXCEPTION == null){
            EXCEPTION = builder.build();
        }
        //判断异常是否在map中
        ResultCode resultCode = EXCEPTION.get(exception.getClass());
        if (resultCode != null){
            return new ResponseResult(resultCode);
        }
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }
}
